<template>
  <div class="employees-container">
    <div class="app-container">
      <!-- <PageTools /> -->
      <PageTools>
        <template #left>
          <span>员工总人数{{ total }}</span>
        </template>
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import')">导入excel</el-button>
          <el-button type="danger" size="small" @click="exportExcel">导出excel</el-button>
          <el-button type="primary" size="small" @click="showDialog = true">新增员工</el-button>
        </template>
      </PageTools>
      <el-card style="margin-top: 10px;">
        <el-table :data="list" border :default-sort="{prop: 'timeOfEntry', order: 'descending'}">
          <el-table-column width="50" label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="员工头像">
            <template #default="{row}">
              <img
                v-imgerror="require('@/assets/common/bigUserHeader.png')"
                :src="row.staffPhoto"
                alt=""
                style="width:50px"
                @click="showCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{row}">
              {{ formatDate(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <!-- <el-table-column label="账户状态" /> -->
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail?userId=${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="prev, pager, next"
            :page-size="size"
            :current-page="page"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <!-- 弹层区域 -->
      <el-dialog title="新增员工" :visible.sync="showDialog">
        <addEmployees @close="showDialog=false" @success="hSuccess" />
      </el-dialog>
      <!-- /生成二维码 -->
      <el-dialog title="二维码" :visible.sync="showCodeDialog">
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
      <el-dialog title="分配角色" :visible.sync="AssignRoleShowDialog">
        <AssignRole :cur-id="curId" @success="AssignRoleShowDialog=false" />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import addEmployees from './empDialog.vue'
import { getEmployees, delEmployees } from '@/api/employess'
import employeesEnum from '@/constant/employees'
import ORCode from 'qrcode'
import AssignRole from './assignRole'

const hireType = {}
employeesEnum.hireType.forEach(item => {
  hireType[item.id] = item.value
})
console.log(hireType, 'hireType')
employeesEnum.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})
export default {
  components: {
    addEmployees, AssignRole
  },
  data() {
    return {
      curId: '',
      AssignRoleShowDialog: false, // 分配角色
      showCodeDialog: false, // 控制二维码
      showDialog: false,
      list: [],
      page: 1,
      size: 5,
      total: 0
    }
  },
  created() {
    this.loadEmployees()
  },
  methods: {
    hAssignRole(id) {
      this.AssignRoleShowDialog = true
      this.curId = id
    },

    showCode(url) {
      this.showCodeDialog = true // dom更新异步的
      // 生成二维码
      this.$nextTick(() => {
        const canvas = this.$refs.myCanvas
        ORCode.toCanvas(canvas, url)
      })
    },
    exportExcel() {
      console.log(this.list, 'list')
      const { tHeader, data } = this.tarnsZhKeyToExcel(this.list)
      // this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
      //   const tHeader = ['Id', 'Title', 'Author', 'Readings', 'Date']
      //   // const filterVal = ['id', 'title', 'author', 'pageviews', 'display_time']
      //   // const list = this.list
      //   const data = [[1, '三体', '刘慈欣', 10000, '2022-11-05'], [2, '西游记', '吴承恩', 10000, '1995-11-05']]
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType
        })
      })
    },
    tarnsZhKeyToExcel(list) {
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // 1.生成表头
      const one = list[0]
      if (!one) return
      const tHeader = Object.keys(one).map(enkey => {
        return mapInfo[enkey]
      })
      // 2.生成表的内容data
      const data = list.map(item => {
        return Object.values(item)
      })
      return { tHeader, data }
    },
    hDel(id) {
      this.$confirm('您确定要删除该员工信息吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await delEmployees(id)
        console.log(res, 'delEmployees')
        if (res.code === 10000) {
          this.$message.success(res.message)
          if (this.size === 1) {
            this.page--
            if (this.page <= 0) {
              this.page = 1
            }
          }
          this.loadEmployees()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    hSuccess() {
      this.total++
      // 技术最大的页码值
      const maxPage = Math.ceil(this.total / this.size)
      // 跳转到最后一页
      this.page = maxPage
      this.showDialog = false
      this.loadEmployees()
    },
    handleCurrentChange(val) {
      this.page = val
      this.loadEmployees()
    },
    formatDate(id) {
      console.log(id, 'id')
      // return hireType[id] || '未知'
      return hireType[id] || '未知'
    },
    async loadEmployees() {
      try {
        const res = await getEmployees({ page: this.page, size: this.size })

        if (res.code !== 10000) return this.$message.error(res.$message)
        this.$message.success(res.message)
        // console.log(res)
        this.list = res.data.rows
        this.total = res.data.total
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

